use std::time::Instant;
use std::env;

fn sieve(n: usize) -> Vec<bool> {
    if n <= 2 {
        return vec![false; n];
    }
    
    let mut is_prime = vec![true; n];
    is_prime[0] = false;
    is_prime[1] = false;
    
    let sqrt_n = (n as f64).sqrt() as usize;
    
    for i in 2..=sqrt_n {
        if is_prime[i] {
            let mut j = i * i;
            while j < n {
                is_prime[j] = false;
                j += i;
            }
        }
    }
    
    is_prime
}

fn main() {
    let mut args = env::args().skip(1);
    let n = args.next().map(|n| n.parse().unwrap()).unwrap_or_else(|| 10_000_000);
    let runs = args.next().map(|n| n.parse().unwrap()).unwrap_or_else(|| 5);
    let print = args.next().is_some();
    
    let mut durations = Vec::new();

    // 预热运行（3次）
    for _ in 0..3 {
        let _ = sieve(n);
    }

    for _ in 0..runs {
        let start = Instant::now();
        let is_prime = sieve(n);
        let duration = start.elapsed();
        if print {
            println!("{is_prime:?}");
        }
        durations.push(duration.as_nanos());
    }

    let total_time: u128 = durations.iter().sum();
    let avg_time = total_time as f64 / runs as f64 / 1_000_000.0;
    println!("Rust   | {:.2} ms", avg_time);
}